package com.plian.system.service.pm.annualdonationrecordmain.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.plian.Tools.*;
import com.plian.Tools.office.WordUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.OrgCache;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CustomCode;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.fr.gsalaryslip.GsalarySlipDao;
import com.plian.system.dto.pm.annualdonationrecordmain.AnnualDonationRecordMainDTO;
import com.plian.system.entity.pm.annualdonationrecord.AnnualDonationRecord;
import com.plian.system.entity.pm.annualdonationrecordmain.AnnualDonationRecordMain;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.listener.AnnualDonationEvent;
import com.plian.system.mapper.pm.annualdonationrecordmain.AnnualDonationRecordMainMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.pdf.OutPdf;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.annualdonationrecord.IAnnualDonationRecordService;
import com.plian.system.service.pm.annualdonationrecordmain.IAnnualDonationRecordMainService;
import com.plian.system.service.pm.property.PropertyService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.vo.pm.annualdonationrecord.AnnualDonationRecordVO;
import com.plian.system.vo.pm.annualdonationrecordmain.*;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.pm.annualdonationrecord.AnnualDonationRecordWrapper;
import com.plian.system.wrapper.pm.annualdonationrecordmain.AnnualDonationRecordMainWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 企业年度捐赠计划备案 服务实现类
 *
 * @author gangan
 * @since 2019-10-24
 */
@Slf4j
@Service
@AllArgsConstructor
public class AnnualDonationRecordMainServiceImpl extends BaseServiceImpl<AnnualDonationRecordMainMapper, AnnualDonationRecordMain> implements IAnnualDonationRecordMainService, BaseFlowService {

    private IAnnualDonationRecordService annualDonationRecordService;

    private IFormCodeService formCodeService;

    private IApprovalMessageService approvalMessageService;

    private FileService fileService;

    private Environment environment;

    private GsalarySlipDao gsalarySlipDao;

    private ApplicationContext applicationContext;

    private AnnualDonationRecordWrapper annualDonationRecordWrapper;

    private AnnualDonationRecordMainWrapper annualDonationRecordMainWrapper;

    private GzwProperties gzwProperties;

    private IOrgService orgService;

    private ISysUserService userService;

    @Autowired
    PropertyService propertyService;

    @Override
    public IPage<AnnualDonationRecordMain> preList(IPage<AnnualDonationRecordMain> page, QueryWrapper queryWrapper) {
        return page.setRecords(baseMapper.preList(page, queryWrapper));
    }

    /**
     * 提交
     *
     * @param id
     * @return
     */
    @Override
    public HashMap<String, Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, null);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String, Object>();
    }

    /**
     * 退回
     *
     * @param id
     * @return
     */
    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState, comment);
    }

    /**
     * 审批完成
     *
     * @param id
     * @return
     */
    @Override
    public Boolean finish(String id) {
        /**
         * 设置审批人和审批时间
         */
        AnnualDonationRecordMain annualDonationRecordMain = getById(id);
        annualDonationRecordMain.setApprovedUser(TokenUtil.getTokenUserId());
        Date now = DateUtil.now();
        annualDonationRecordMain.setApprovedTime(now);
        if (StringUtil.isBlank(annualDonationRecordMain.getFilingCode())) {
            String code = formCodeService.getFilingCode(FormTypeConstant.PM_ANNUALDONATIONRECORD_FORM);
            annualDonationRecordMain.setFilingCode(gzwProperties.getCodeStartName() + "捐备〔" + code.substring(0, 4) + "〕" + code.substring(code.length() - 3) + "号");
        }
        updateById(annualDonationRecordMain);
        boolean result = handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, "审批通过！");
        if (result && Integer.valueOf(annualDonationRecordMain.getYear()) >= 2021) {
            PageData pd = new PageData();
            pd.put("year", annualDonationRecordMain.getYear());
            pd.put("unit", annualDonationRecordMain.getReportCompanyId());
            AnnualDonationRecordMainVO annualDonationRecordMainVO = new AnnualDonationRecordMainVO();
            annualDonationRecordMainVO.setYear(annualDonationRecordMain.getYear());
            List<AnnualDonationRecordMain> annualDonationRecordMains = list(new LambdaQueryWrapper<AnnualDonationRecordMain>()
                    .eq(AnnualDonationRecordMain::getYear, annualDonationRecordMain.getYear()).eq(AnnualDonationRecordMain::getStatus, FormStatusConstant.FINISH)
                    .eq(AnnualDonationRecordMain::getCreateCompanyId, annualDonationRecordMain.getReportCompanyId())
                    .orderByDesc(AnnualDonationRecordMain::getCreateTime));
            List<AnnualDonationRecord> annualDonationRecords = annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                    .in(AnnualDonationRecord::getParentId, annualDonationRecordMains.stream().map(AnnualDonationRecordMain::getId).collect(Collectors.toList())));
            annualDonationRecordMainVO.setAnnualDonationRecordVOS(annualDonationRecordWrapper.entityToVO(annualDonationRecords));
            annualDonationRecordMainVO.setReportCompanyName(OrgCache.orgIdToName(annualDonationRecordMain.getReportCompanyId()));
            try {
                String[] fhTableTypeCodes = {"0", "6"};
                pd.put("fhTableTypeCodes", fhTableTypeCodes);
                List<PageData> list = gsalarySlipDao.findAllZb(pd);
                if (CollectionUtil.isNotEmpty(list)) {
                    for (PageData gsalarySlip : list) {
                        AnnualDonationRecordMainVO vo = new AnnualDonationRecordMainVO();
                        BeanUtils.copyProperties(annualDonationRecordMainVO, vo);
                        vo.setReportId(gsalarySlip.getString("id"));
                        applicationContext.publishEvent(new AnnualDonationEvent(vo));
                    }
                }
            } catch (Exception e) {
                log.error(ExceptionUtils.getFullStackTrace(e));
                log.error("" + e);
            }

        }
        return result;
    }

    @Override
    public Boolean checkIsExisted(Long id, String code) {
        return null;
    }


    @Override
    public boolean saveOrUpdate(AnnualDonationRecordMain annualDonationRecordMain) {
        if (!Optional.ofNullable(annualDonationRecordMain.getStatus()).isPresent()) {
            annualDonationRecordMain.setStatus(UNREVIEWED);
        }
        boolean flag = false;
        if (!Optional.ofNullable(annualDonationRecordMain.getId()).isPresent()) {
            annualDonationRecordMain.setVersion("1");
            annualDonationRecordMain.setCode(formCodeService.getCode(FormTypeConstant.PM_ANNUALDONATIONRECORD_FORM));
            annualDonationRecordMain.setFormType(String.valueOf(FormTypeConstant.PM_ANNUALDONATIONRECORD_FORM));
            flag = true;
        }
        boolean result = super.saveOrUpdate(annualDonationRecordMain);
        if (flag) {
            fileService.saveAll(String.valueOf(annualDonationRecordMain.getId()), annualDonationRecordMain.getDocList());
        } else {
            fileService.edit(String.valueOf(annualDonationRecordMain.getId()), annualDonationRecordMain.getDocList());
        }
        if (StringUtil.isNotBlank(annualDonationRecordMain.getAttachIds())) {
            fileService.upYthFile(annualDonationRecordMain.getAttachIds(), String.valueOf(annualDonationRecordMain.getId()));
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            AnnualDonationRecordMain annualDonationRecordMain = getById(id);
            if (annualDonationRecordMain == null) {
                return false;
            } else if (annualDonationRecordMain.getStatus() != null &&
                    (annualDonationRecordMain.getStatus() != FormStatusConstant.STASH && annualDonationRecordMain.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
        }
        return super.deleteLogic(ids);
    }


    @Override
    public String checkYear(Long id, Long reportCompanyId, Date year) {
        String result;
        List<AnnualDonationRecordMain> list = list(new QueryWrapper<AnnualDonationRecordMain>().eq("report_company_id", reportCompanyId)
                .lambda().eq(AnnualDonationRecordMain::getYear, year));
        if (list.size() > 0) {
            if (id == null || !id.equals(list.get(0).getId())) {
                result = "已存在初始化数据，请不要多次初始化";
                return result;
            }
        }
        return null;
    }

    @Override
    public String checkIsExisted(Long id, String code, String filingCode) {
        String result = "";
        if (Optional.ofNullable(code).isPresent()) {
            AnnualDonationRecordMain annualDonationRecordMain = new AnnualDonationRecordMain();
            annualDonationRecordMain.setCode(code);
            if (Optional.ofNullable(getOne(Condition.getQueryWrapper(annualDonationRecordMain))).isPresent()) {
                if (id == null || !id.equals(getOne(Condition.getQueryWrapper(annualDonationRecordMain)).getId())) {
                    result = "单据编码已存在";
                }
            }
        }
        if (Optional.ofNullable(filingCode).isPresent()) {
            AnnualDonationRecordMain annualDonationRecordMain = new AnnualDonationRecordMain();
            annualDonationRecordMain.setCode(filingCode);
            if (Optional.ofNullable(getOne(Condition.getQueryWrapper(annualDonationRecordMain))).isPresent()) {
                if (id == null || !id.equals(getOne(Condition.getQueryWrapper(annualDonationRecordMain)).getId())) {
                    result = "单据备案编号已存在";
                }
            }
        }
        return result;
    }


    @Override
    public R<AnnualDonationRecordMainVO> getDetailObj(AnnualDonationRecordMainVO annualDonationRecordMainVO) {
        if (!Optional.ofNullable(annualDonationRecordMainVO).isPresent()) {
            return new R(CommonCode.FAIL);
        }
        annualDonationRecordMainVO.setAnnualDonationRecordVOS(annualDonationRecordWrapper
                .entityToVO(annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                        .eq(AnnualDonationRecord::getParentId, annualDonationRecordMainVO.getId()))));
        return R.data(annualDonationRecordMainVO);
    }

    @Override
    public R<AnnualDonationRecordMainVO> getPreDetailObj(AnnualDonationRecordMainVO annualDonationRecordMainVO) {
        if (!Optional.ofNullable(annualDonationRecordMainVO).isPresent()) {
            return new R(CommonCode.FAIL);
        }

        annualDonationRecordMainVO.setAnnualDonationRecordVOS(annualDonationRecordWrapper.entityToVO(
                annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                        .eq(AnnualDonationRecord::getParentId, annualDonationRecordMainVO.getId()).eq(AnnualDonationRecord::getDef1, 0))));
        return R.data(annualDonationRecordMainVO);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean submit(AnnualDonationRecordMain annualDonationRecordMain) {
        boolean result = saveOrUpdate(annualDonationRecordMain);
        if (Optional.ofNullable(annualDonationRecordMain.getAnnualDonationRecords()).isPresent() && !annualDonationRecordMain.getAnnualDonationRecords().isEmpty()) {
            annualDonationRecordMain.getAnnualDonationRecords().forEach(v -> {
                v.setParentId(annualDonationRecordMain.getId());
                if (Optional.ofNullable(v.getIsDeleted()).isPresent() && v.getIsDeleted().intValue() == 1) {
                    annualDonationRecordService.removeById(v.getId());
                } else {
                    v.setDef1("0");
                    annualDonationRecordService.saveOrUpdate(v);
                }
            });
        }
        return result;
    }


    @Override
    public AnnualDonationRecordMainVO setChild(AnnualDonationRecordMainVO annualDonationRecordMainVO) {
        if (Optional.ofNullable(annualDonationRecordMainVO).isPresent()) {
            annualDonationRecordMainVO.setAnnualDonationRecordVOS(annualDonationRecordWrapper.entityToVO(
                    annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                            .eq(AnnualDonationRecord::getParentId, annualDonationRecordMainVO.getId()))));
        }
        return annualDonationRecordMainVO;
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id
     * @param updateStatus
     * @return
     */
    private Boolean handleStatus(Long id, int updateStatus, String comment) {
        try {
            AnnualDonationRecordMain annualDonationRecordMain = getById(id);
            annualDonationRecordMain.setStatus(updateStatus);

            if (YthConstant.DATA_NINGBO.equals(annualDonationRecordMain.getDataSource())) {
                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT) {
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(annualDonationRecordMain.getDataSourceId());
                    approvalMessage.setOpinion(comment);
                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                    approvalMessage.setFormType(Integer.valueOf(annualDonationRecordMain.getFormType()));
                    approvalMessage.setFilingCode(annualDonationRecordMain.getCode());
                    approvalMessageService.save(approvalMessage);
                }
            }

            updateById(annualDonationRecordMain);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }


    @Override
    public File buildpdf(Long id) {
        AnnualDonationRecordMainVO bean = annualDonationRecordMainWrapper.entityToVO(getById(id));
        bean = setChild(bean);
        Map<String, String> images = new HashMap<>(16);
        File file = null;

        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            InputStream inputStream = resourceLoader.getResource("annualdonationrecordmain.pdf").getInputStream();
            //通过将文件转换为临时文件进行操作
            File model = File.createTempFile("model", ".png");
            try {
                FileUtils.copyInputStreamToFile(inputStream, model);
            } finally {
                //关闭IO
                IOUtils.closeQuietly(inputStream);
            }
            InputStream inputStream2 = resourceLoader.getResource("4DB6230D1BF52D9A012171F8493CF278.png").getInputStream();
            //通过将文件转换为临时文件进行操作
            File image = File.createTempFile("logoImage1", ".png");
            try {
                FileUtils.copyInputStreamToFile(inputStream2, image);
            } finally {
                //关闭IO
                IOUtils.closeQuietly(inputStream2);
            }
            images.put("logoImage1", !image.exists() ? "" : image.getAbsolutePath());
            if (bean != null && model.exists()) {
                Map<String, Object> data = OutPdf.beanToMap(bean);

                List<AnnualDonationRecordVO> temp = bean.getAnnualDonationRecordVOS();
                BigDecimal sum = BigDecimal.ZERO;
                int x = 0;
                for (; x < temp.size(); x++) {
                    data.put("a.id." + x, x + 1);
                    data.put("a.donationCompanyName." + x, temp.get(x).getDonationCompanyName());
                    data.put("a.donationBasis." + x, temp.get(x).getDonationBasis());
                    data.put("a.donationObject." + x, temp.get(x).getDonationObject());
                    data.put("a.donationCause." + x, temp.get(x).getDonationCause());
                    data.put("a.donationPropertyComposition." + x, temp.get(x).getDonationPropertyComposition());
                    data.put("a.donationAmount." + x, temp.get(x).getDonationAmount());
                    data.put("a.donationTime." + x, temp.get(x).getDonationTime());
                    if (temp.get(x).getDonationAmount() != null) {
                        sum = sum.add(temp.get(x).getDonationAmount());
                    }
                }
                data.put("a.id." + x, x + 1);
                data.put("a.donationAmount." + x, sum);

                String fileName = model.getPath();
                PdfReader reader = new PdfReader(fileName);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                /* 将要生成的目标PDF文件名称 */
                PdfStamper ps = new PdfStamper(reader, bos);
                /* 使用中文字体 */
                BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                ArrayList<BaseFont> fontList = new ArrayList<>();
                fontList.add(bf);

                /* 取出报表模板中的所有字段 */
                AcroFields fields = ps.getAcroFields();
                fields.setSubstitutionFonts(fontList);
                for (String key : data.keySet()) {
                    if (data.get(key) != null) {
                        String value = data.get(key).toString();
                        if (data.get(key) instanceof Date) {
                            value = processDate((Date) data.get(key));
                        }
                        fields.setField(key, value);
                    }
                }

				/*if (images!=null) {
					for (String key : images.keySet()) {
						if (!StringUtil.isEmpty(images.get(key))) {
							//待加入图片的文字域,设置为隐藏;不然会遮挡掉图片的
							OutPdf.insertImage(fields, ps, key, images.get(key));
						}
					}
				}*/
                /* 必须要调用这个，否则文档不会生成的 */
                ps.setFormFlattening(true);
                ps.close();
                File dir = new File(model.getParent());
                String classFullName = bean.getClass().getName();
                file = File.createTempFile(classFullName.substring(classFullName.lastIndexOf(".")), ".pdf", dir);
                OutputStream fos = new FileOutputStream(file);
                fos.write(bos.toByteArray());
                fos.flush();
                fos.close();
                bos.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    private static String processDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return date == null ? "" : format.format(date);
    }

    @Override
    public File createReceptFile(Long id) {
        try {
            int length = 0;
            AnnualDonationRecordMainVO bean = annualDonationRecordMainWrapper.entityToVO(getById(id));
            bean = setChild(bean);
            BigDecimal sum = BigDecimal.ZERO;
            length = bean.getAnnualDonationRecordVOS() == null ? 0 : bean.getAnnualDonationRecordVOS().size();
            String[][] son = new String[length][8];
            for (int i = 0; i < length; i++) {
                son[i][0] = String.valueOf(i + 1);
                son[i][1] = bean.getAnnualDonationRecordVOS().get(i).getDonationCompanyName();
                son[i][2] = bean.getAnnualDonationRecordVOS().get(i).getDonationBasis();
                son[i][3] = bean.getAnnualDonationRecordVOS().get(i).getDonationObject();
                son[i][4] = bean.getAnnualDonationRecordVOS().get(i).getDonationCause();
                son[i][5] = bean.getAnnualDonationRecordVOS().get(i).getDonationPropertyComposition();
                if (Optional.ofNullable(bean.getAnnualDonationRecordVOS().get(i).getDonationAmount()).isPresent()) {
                    son[i][6] = bean.getAnnualDonationRecordVOS().get(i).getDonationAmount().toString();
                    sum = sum.add(bean.getAnnualDonationRecordVOS().get(i).getDonationAmount());
                } else {
                    son[i][6] = "";
                }
                if (Optional.ofNullable(bean.getAnnualDonationRecordVOS().get(i).getDonationTime()).isPresent()) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
                    son[i][7] = simpleDateFormat.format(bean.getAnnualDonationRecordVOS().get(i).getDonationTime());
                } else {
                    son[i][7] = "";
                }
            }

            Document document = new Document(PageSize.A4, 90, 83, 30, 40);
            FileOutputStream fs;
            BaseFont bfHeiTi;
            BaseFont bfST;
            BaseFont test;
            BaseFont bfbt;

            String filingCode = bean.getFilingCode();
            //File pdffile = File.createTempFile(id.toString(), ".pdf");
            if (StringUtil.isBlank(filingCode)) {
                filingCode = "企业年度捐赠计划备案";
            }
            File pdffile = File.createTempFile(filingCode + "&&", ".pdf");
            if (pdffile.exists()) {
                pdffile.delete();
            }

            fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
            PdfWriter.getInstance(document, fs);

            // 打开文档
            document.open();
            bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            // 创建了一页
            Font font_Zhengwen = new Font(bfST, 10.0f, Font.NORMAL, BaseColor.BLACK);
            // 添加标题
            Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
            Font font_biaotou1 = new Font(test, 12.0f, Font.NORMAL, BaseColor.BLACK);
            Font font_biaotou2 = new Font(bfbt, 12.0f, Font.NORMAL, BaseColor.BLACK);

            // 创建一个段落
            String title = bean.getYear() + "年度捐赠计划备案表";
            Paragraph biaoti = new Paragraph(title, font_Biaoti);
            biaoti.setAlignment(1);
            biaoti.setSpacingAfter(20f);
            document.add(biaoti);

            float[] widths = {30f, 75f, 45f, 45f, 45f, 45f, 45f, 45f};// 设置表格的列宽
            PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格
            table.setSpacingBefore(10f);// 设置表格上面空白宽度
            table.setSpacingAfter(0f);// 设置表格下面空白宽度
            table.setTotalWidth(480);// 设置表格的宽度
            PdfPCell cell = new PdfPCell();
            PdfPCell cell2 = new PdfPCell();
            cell.setMinimumHeight(25f);
            cell2.setMinimumHeight(25f);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPaddingTop(5);
            cell.setPaddingBottom(5);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setPaddingTop(5);
            cell2.setPaddingBottom(5);
            //table.setLockedWidth(true);

            PdfPCell cell3 = new PdfPCell();
            PdfPCell cell4 = new PdfPCell();
            cell3.setMinimumHeight(25f);
            cell4.setMinimumHeight(25f);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.setLockedWidth(true);

            //正式开始
            if (StringUtil.isBlank(bean.getFilingCode())) {
                bean.setFilingCode("");
            }
            cell3.setPhrase(new Paragraph("备案编号：" + bean.getFilingCode(), font_Zhengwen));
            cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell3.disableBorderSide(13);
            cell3.setColspan(4);
            table.addCell(cell3);
            cell4.setPhrase(new Paragraph("金额单位：万元", font_Zhengwen));
            cell4.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell4.disableBorderSide(13);
            cell4.setColspan(4);
            table.addCell(cell4);

            cell.setPhrase(new Paragraph("填报单位(盖章)", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getReportCompanyName(), font_Zhengwen));
            cell2.setColspan(6);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("序号", font_biaotou2));
            cell.setColspan(1);
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠企业", font_biaotou2));
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠依据", font_biaotou2));
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠对象", font_biaotou2));
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠事由", font_biaotou2));
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠财产" +
                    "构成", font_biaotou2));
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠金额", font_biaotou2));
            table.addCell(cell);

            cell.setPhrase(new Paragraph("捐赠时间", font_biaotou2));
            table.addCell(cell);

            length = son.length < 8 ? 8 : son.length;
            for (int i = 0; i < length; i++) {
                for (int j = 0; j < 8; j++) {
                    if (i < son.length) {
                        cell2.setPhrase(new Paragraph(son[i][j], font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    cell2.setColspan(1);
                    cell2.setRowspan(1);
                    table.addCell(cell2);
                }
            }
            cell.setPhrase(new Paragraph("合计", font_biaotou2));
            table.addCell(cell);

            cell2.setPhrase(new Paragraph("", font_Zhengwen));
            table.addCell(cell2);
            table.addCell(cell2);
            table.addCell(cell2);
            table.addCell(cell2);
            table.addCell(cell2);

            cell2.setPhrase(new Paragraph(sum.toString(), font_Zhengwen));
            table.addCell(cell2);

            cell2.setPhrase(new Paragraph("", font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("备案意见", font_biaotou2));
            cell.setColspan(2);
            cell.setMinimumHeight(150f);
            table.addCell(cell);

            if (bean.getStatus() == 3) {
                String approvedTimeStr = "";
                if (Optional.ofNullable(bean.getApprovedTime()).isPresent()) {
                    approvedTimeStr = new SimpleDateFormat("yyyy年MM月dd日").format(bean.getApprovedTime());
                }
                cell2.setPhrase(new Paragraph("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "同意备案"
                        + "\n\n\n\n\n\n" + "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0审批人：" + bean.getApprovedUserName()
                        + "\n\n\n" + "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0" + approvedTimeStr, font_Zhengwen));
                cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
            } else {
                cell2.setPhrase(new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n\n审批人：" +
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0"
                        + "\n\n\n" + "年        月        日", font_Zhengwen));
                cell2.setHorizontalAlignment(Element.ALIGN_RIGHT);
            }
            cell2.setColspan(6);
            table.addCell(cell2);

            document.add(table);
            document.close();
            return pdffile;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return null;
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<AnnualDonationRecordMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(AnnualDonationRecordMain::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<AnnualDonationRecordMain> annualDonationRecordMains = list(queryWrapper);
        List<AnnualDonationRecordMainVO> annualDonationRecordMainVOS = annualDonationRecordMainWrapper.entityToVO(annualDonationRecordMains);
        List<PageData> pageDataList = new ArrayList<>();
        try {
            if (CollectionUtil.isNotEmpty(annualDonationRecordMainVOS)) {
                for (AnnualDonationRecordMainVO vo : annualDonationRecordMainVOS) {
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getReportCompanyName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getReportCompanyId());
                    pd.put("formType", FormTypeConstant.PM_ANNUALDONATIONRECORD_FORM);
                    pd.put("orgName", vo.getReportCompanyName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.PM_ANNUALDONATIONRECORD_FORM);
    }

    @Override
    public R<AnnualDonationRecordMainVO> refByYear(String year) {
        if (StringUtil.isBlank(year)) {
            return new R(CustomCode.builder().message("年度为空").code(1999).success(false).build());
        }

        List<AnnualDonationRecordMain> annualDonationRecordMains = list(new LambdaQueryWrapper<AnnualDonationRecordMain>()
                .eq(AnnualDonationRecordMain::getYear, year).eq(AnnualDonationRecordMain::getStatus, FormStatusConstant.FINISH)
                .eq(AnnualDonationRecordMain::getCreateCompanyId, TokenUtil.getTokenOrgId())
                .orderByDesc(AnnualDonationRecordMain::getCreateTime));
        AnnualDonationRecordMainVO vo = new AnnualDonationRecordMainVO();
        if (CollectionUtil.isNotEmpty(annualDonationRecordMains)) {
            vo.setFilingCode(annualDonationRecordMains.stream().map(AnnualDonationRecordMain::getFilingCode).collect(Collectors.joining(StringPool.COMMA)));
            vo.setAnnualDonationRecordVOS(annualDonationRecordWrapper.entityToVO(
                    annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                            .in(AnnualDonationRecord::getParentId, annualDonationRecordMains.stream().map(AnnualDonationRecordMain::getId).collect(Collectors.toList()))
                            .eq(AnnualDonationRecord::getDef1, 0))));
        }

        return R.data(vo);
    }

    @Override
    public File buildword(Long id, HttpServletResponse response) {
        AnnualDonationRecordMainVO bean = annualDonationRecordMainWrapper.entityToVO(getById(id));
        File file = null;
        try {
            if (bean != null) {
                Map<String, Object> data = new HashMap<>(16);
                data.put("year", bean.getYear());
                data.put("filingCode", bean.getFilingCode());
                data.put("reportCompanyName", bean.getReportCompanyName());

                AnnualDonationRecord annualDonationRecord = new AnnualDonationRecord();
                annualDonationRecord.setParentId(bean.getId());
                List<AnnualDonationRecordVO> annualDonationRecordVOS = annualDonationRecordWrapper.entityToVO(annualDonationRecordService.list(Condition.getQueryWrapper(annualDonationRecord)));

                BigDecimal amount = new BigDecimal(0);
                if (CollectionUtil.isNotEmpty(annualDonationRecordVOS)) {
                    for (AnnualDonationRecordVO annualDonationRecordVO : annualDonationRecordVOS) {
                        amount = BigDecimalUtil.add(amount, annualDonationRecordVO.getDonationAmount());
                    }
                }

                BigDecimal bigDecimal = new BigDecimal(0);
                if (CollectionUtil.isNotEmpty(annualDonationRecordVOS)) {
                    data.put("annualDonationRecordVOS", annualDonationRecordVOS);
                    for (AnnualDonationRecordVO donationRecordVO : annualDonationRecordVOS) {
                        bigDecimal = BigDecimalUtil.add(bigDecimal, donationRecordVO.getDonationAmount());
                    }
                }
                data.put("account", bigDecimal);

                String realPath = environment.getProperty("doc.path") + id + ".doc";

                //备案编号
                String filingId = bean.getFilingCode();
                if (filingId == null) {
                    file = WordUtil.generateWord(data, realPath, "annualDonationRecordMain.doc", "annualDonationRecordMain.ftl");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
                } else {
                    file = WordUtil.generateWord(data, realPath, filingId + ".doc", "annualDonationRecordMain.ftl");
                    String fileName = new String(file.getName().getBytes("GB2312"), "ISO_8859_1");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                }
                InputStream inputStream = new FileInputStream(file);
                // 激活下载操作
                OutputStream os = response.getOutputStream();
                // 循环写入输出流
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                // 这里主要关闭。
                os.close();
                inputStream.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    @Override
    public List<AnnualDonationRecordStatisticalVO> annualDonationRecordStatistical(AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        List<AnnualDonationRecordStatisticalVO> voList = baseMapper.annualDonationRecordStatistical(annualDonationRecordMainDTO.getOrgIds(), annualDonationRecordMainDTO.getYear());
        ;
        if (CollectionUtil.isNotEmpty(voList)) {
            AnnualDonationRecordStatisticalVO sumVO = new AnnualDonationRecordStatisticalVO();
            sumVO.setRecordCode("合计");
            sumVO.setDonationAmount(new BigDecimal(0));
            for (AnnualDonationRecordStatisticalVO statisticalVO : voList) {
                sumVO.setDonationAmount(BigDecimalUtil.add(sumVO.getDonationAmount(), statisticalVO.getDonationAmount()));
            }
            voList.add(sumVO);
        }
        voList.forEach(record -> {
            BigDecimal amount = record.getDonationAmount().setScale(4, BigDecimal.ROUND_HALF_UP);
            String amountStr = amount.toString();
            record.setDonationAmountStr(amountStr);
        });
        return voList;
    }

    @Override
    public List<AnnualDonationRecordStatisticalDetailVO> annualDonationRecordStatisticalDetail(AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        return baseMapper.annualDonationRecordStatisticalDetail(annualDonationRecordMainDTO.getId());
    }

    @Override
    public ReportReturnVO annualDonationYearStatistical(AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        List<AnnualDonationYearStatisticalVO> dataList = new ArrayList<>();
        String year = annualDonationRecordMainDTO.getYear();
        String lastYear = String.valueOf(Integer.valueOf(annualDonationRecordMainDTO.getYear()) - 1);
        ReportVO reportVO = new ReportVO();
        reportVO.addHeader(HeaderVO.builder().key("index").title("序号").build())
                .addHeader(HeaderVO.builder().key("reportCompanyName").title("企业名称").build());

        switch (annualDonationRecordMainDTO.getStatisticalType()) {
            case 1:
                reportVO.addHeader(HeaderVO.builder().key("lastYearDonationAmount").title(lastYear + "年度捐赠计划（万元）").build())
                        .addHeader(HeaderVO.builder().key("lastYearExecuteAmount").title(lastYear + "年实际捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("donationAmount").title(year + "年度捐赠计划（万元）").build());

                dataList = baseMapper.annualDonationYearStatistical(annualDonationRecordMainDTO.getOrgIds(), year, lastYear);
                break;
            case 2:
                reportVO.addHeader(HeaderVO.builder().key("donationAmount").title(year + "年度捐赠计划（万元）").build())
                        .addHeader(HeaderVO.builder().key("executeAmount").title(year + "年实际捐赠金额（万元）").build());
                dataList = baseMapper.annualDonationExecuteYearStatistical(annualDonationRecordMainDTO.getOrgIds(), year);
                break;
            default:
                break;
        }

        ReportReturnVO reportReturnVO = new ReportReturnVO();
        reportVO.setData(dataList);
        if (CollectionUtil.isNotEmpty(dataList)) {
            AnnualDonationYearStatisticalVO sumVO = new AnnualDonationYearStatisticalVO();
            sumVO.setReportCompanyName("合计");
            sumVO.setLastYearDonationAmount(new BigDecimal(0));
            sumVO.setDonationAmount(new BigDecimal(0));
            sumVO.setExecuteAmount(new BigDecimal(0));
            sumVO.setLastYearExecuteAmount(new BigDecimal(0));
            for (AnnualDonationYearStatisticalVO statisticalVO : dataList) {
                sumVO.setLastYearDonationAmount(BigDecimalUtil.add(sumVO.getLastYearDonationAmount(), statisticalVO.getLastYearDonationAmount()));
                sumVO.setDonationAmount(BigDecimalUtil.add(sumVO.getDonationAmount(), statisticalVO.getDonationAmount()));
                sumVO.setExecuteAmount(BigDecimalUtil.add(sumVO.getExecuteAmount(), statisticalVO.getExecuteAmount()));
                sumVO.setLastYearExecuteAmount(BigDecimalUtil.add(sumVO.getLastYearExecuteAmount(), statisticalVO.getLastYearExecuteAmount()));
            }
            dataList.add(sumVO);
        }
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public ReportReturnVO annualDonationYearStatisticalDetail(AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        List<AnnualDonationYearStatisticalDetailVO> dataList = new ArrayList<>();

        ReportVO reportVO = new ReportVO();
        reportVO.addHeader(HeaderVO.builder().key("index").title("序号").build())
                .addHeader(HeaderVO.builder().key("donationCompanyName").title("捐赠企业").build());
        switch (annualDonationRecordMainDTO.getDetailColumnName()) {
            case "lastYearDonationAmount":
                dataList = baseMapper.annualDonationYearStatisticalDetail(annualDonationRecordMainDTO.getLastYear(), annualDonationRecordMainDTO.getReportCompanyId());
                reportVO.addHeader(HeaderVO.builder().key("donationAmount").title(annualDonationRecordMainDTO.getLastYear() + "年计划捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("donationObject").title(annualDonationRecordMainDTO.getLastYear() + "年捐赠对象").build())
                        .addHeader(HeaderVO.builder().key("donationCause").title(annualDonationRecordMainDTO.getLastYear() + "年捐赠事由").build());
                break;
            case "lastYearExecuteAmount":
                dataList = baseMapper.annualDonationExecuteYearStatisticalDetail(annualDonationRecordMainDTO.getLastYear(), annualDonationRecordMainDTO.getReportCompanyId());
                reportVO.addHeader(HeaderVO.builder().key("donationAmount").title(annualDonationRecordMainDTO.getLastYear() + "年计划捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("donationObject").title(annualDonationRecordMainDTO.getLastYear() + "年捐赠对象").build())
                        .addHeader(HeaderVO.builder().key("donationCause").title(annualDonationRecordMainDTO.getLastYear() + "年捐赠事由").build())
                        .addHeader(HeaderVO.builder().key("actualDonationAmount").title(annualDonationRecordMainDTO.getLastYear() + "年实际捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("actualDonationTime").title("实际捐赠时间").build());
                break;
            case "donationAmount":
                dataList = baseMapper.annualDonationYearStatisticalDetail(annualDonationRecordMainDTO.getYear(), annualDonationRecordMainDTO.getReportCompanyId());
                reportVO.addHeader(HeaderVO.builder().key("donationAmount").title(annualDonationRecordMainDTO.getYear() + "年计划捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("donationObject").title(annualDonationRecordMainDTO.getYear() + "年捐赠对象").build())
                        .addHeader(HeaderVO.builder().key("donationCause").title(annualDonationRecordMainDTO.getYear() + "年捐赠事由").build());
                break;
            case "executeAmount":
                dataList = baseMapper.annualDonationExecuteYearStatisticalDetail(annualDonationRecordMainDTO.getYear(), annualDonationRecordMainDTO.getReportCompanyId());
                reportVO.addHeader(HeaderVO.builder().key("donationAmount").title(annualDonationRecordMainDTO.getYear() + "年计划捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("donationObject").title(annualDonationRecordMainDTO.getYear() + "年捐赠对象").build())
                        .addHeader(HeaderVO.builder().key("donationCause").title(annualDonationRecordMainDTO.getYear() + "年捐赠事由").build())
                        .addHeader(HeaderVO.builder().key("actualDonationAmount").title(annualDonationRecordMainDTO.getYear() + "年实际捐赠金额（万元）").build())
                        .addHeader(HeaderVO.builder().key("actualDonationTime").title("实际捐赠时间").build());
                break;
            default:
                break;
        }

        ReportReturnVO reportReturnVO = new ReportReturnVO();
        reportVO.setData(dataList);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public String saveAnnualDonationRecordReform(String data) {
        YthResult ythResult = new YthResult();
        //成功的id集合
        List<String> successIds = new ArrayList<>();
        //失败的id集合
        List<String> failIds = new ArrayList<>();
        //失败的原因
        List<String> failReasons = new ArrayList<>();
        //将json字符串转换成list
        List<AnnualDonationRecordMain> dataList = JSON.parseArray(data, AnnualDonationRecordMain.class);
        //判断list是否为空
        if (CollectionUtil.isNotEmpty(dataList)) {
            //根据datasourceIds 查询出所有的数据
            List<AnnualDonationRecordMain> list = list(new LambdaQueryWrapper<AnnualDonationRecordMain>()
                    .in(AnnualDonationRecordMain::getDataSourceId, dataList.stream()
                            .map(AnnualDonationRecordMain::getDataSourceId).toArray()));
            //如果数据库中有数据，就更新，没有就新增
            for (AnnualDonationRecordMain entity : dataList) {
                String dataSourceId = entity.getDataSourceId();
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> olIds = list.stream().map(AnnualDonationRecordMain::getDataSourceId).collect(Collectors.toList());
                    //判断数据库中是否有数据
                    if (olIds.contains(dataSourceId)) {
                        for (AnnualDonationRecordMain oldEntity : list) {
                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
                                successIds.add(dataSourceId);
                                entity.setId(oldEntity.getId());
                                entity.setDataSource(YthConstant.DATA_NINGBO);
                                extracted(entity);
                                submit(entity);
                                list.remove(oldEntity);
                                break;
                            }
                        }
                    } else {
                        //如果数据库中没有数据，就新增
                        entity.setDataSource(YthConstant.DATA_NINGBO);
                        extracted(entity);
                        submit(entity);
                        successIds.add(entity.getDataSourceId());
                    }
                } else {
                    entity.setDataSource(YthConstant.DATA_NINGBO);
                    extracted(entity);
                    submit(entity);
                    successIds.add(entity.getDataSourceId());
                }
            }
        } else {
            failReasons.add("数据为空");
        }
        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    /**
     * 将数字宁波过来的数据人员id，
     *
     * @param entity
     */
    private void extracted(AnnualDonationRecordMain entity) {
        Map<String, String> orgSourceIds = orgService.getSourceId();
        Map<String, String> userSourceIds = userService.getSourceId();

        String reportCompanyId = orgSourceIds.get(entity.getReportCompanyId());
        String createUser = userSourceIds.get(entity.getCreateUser());
        if (StringUtils.isNotBlank(reportCompanyId)) {
            entity.setReportCompanyId(reportCompanyId);
            entity.setCreateCompanyId(reportCompanyId);
        }
        if (StringUtils.isNotBlank(createUser)) {
            entity.setCreateUser(createUser);
            entity.setUpdateUser(createUser);
        }
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        //从表
        if (CollectionUtil.isNotEmpty(entity.getAnnualDonationRecords())) {
            entity.getAnnualDonationRecords().forEach(item -> {
                if (StringUtils.isNotBlank(reportCompanyId)) {
                    item.setCreateCompanyId(reportCompanyId);
                }
                if (StringUtils.isNotBlank(item.getDonationCompany())) {
                    String propertyId = propertyService.findByOrgCode(item.getDonationCompany());
                    if (StringUtil.isNotBlank(propertyId)) {
                        item.setDonationCompany(propertyId);
                    }
                }
                item.setDataSource(YthConstant.DATA_NINGBO);
            });
        }

    }
    public Boolean checkJzjh(Long id){
        Boolean isTwoYear=false;
        Boolean isTreeYear=false;
        Boolean bo=false;
        Boolean isTree=false;
        List<AnnualDonationRecord> records=annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                .eq(AnnualDonationRecord::getParentId, id));
        BigDecimal amount=new BigDecimal(0);
        if(records!=null&&records.size()>0){
            for (AnnualDonationRecord record: records) {//判断一次性捐赠金额超过五万或者累计超过100万的
                if(record!=null&&record.getDonationAmount()!=null){
                    if(record.getDonationAmount().compareTo(new BigDecimal(5))>=0){
                        return true;
                    }
                    amount=amount.add(record.getDonationAmount());
                }
            }
            if(amount.compareTo(new BigDecimal(100))>=0){
                return true;
            }

            AnnualDonationRecordMain  annualDonationRecordMain=this.getOne(new LambdaQueryWrapper<AnnualDonationRecordMain>()
                    .eq(AnnualDonationRecordMain::getId, id));
            if(annualDonationRecordMain!=null&& StringUtil.isNotBlank(annualDonationRecordMain.getYear())){//判断连续三年捐赠同一对象
                Integer year=Integer.valueOf(annualDonationRecordMain.getYear());
                List<AnnualDonationRecordMain>  lastAnnualDonationRecordMainList=this.list(new LambdaQueryWrapper<AnnualDonationRecordMain>()
                        .eq(AnnualDonationRecordMain::getYear, String.valueOf(year-1)).eq(AnnualDonationRecordMain::getStatus,3));
                if(lastAnnualDonationRecordMainList!=null&&lastAnnualDonationRecordMainList.size()>0){
                    List<AnnualDonationRecord> twoYearrecords=annualDonationRecordService.list(new LambdaQueryWrapper<AnnualDonationRecord>()
                            .eq(AnnualDonationRecord::getParentId, id));
                    for (AnnualDonationRecord record: records) {
                        if(getCheckRecordList(twoYearrecords,record)){
                            isTwoYear=true;
                            break;
                        }
                    }
                    List<AnnualDonationRecordMain>  lastLastAnnualDonationRecordMainList=this.list(new LambdaQueryWrapper<AnnualDonationRecordMain>()
                            .eq(AnnualDonationRecordMain::getYear, String.valueOf(year-2)).eq(AnnualDonationRecordMain::getStatus,3));
                    if(lastLastAnnualDonationRecordMainList!=null&&lastLastAnnualDonationRecordMainList.size()>0){
                        for (AnnualDonationRecord record: records) {
                            if(getCheckRecordList(twoYearrecords,record)){
                                isTreeYear=true;
                                break;
                            }
                        }
                    }
                }
            }
            if(isTwoYear&&isTreeYear){//判断是否连续三年都捐赠一个企业
                return true;
            }

        }




        return bo;
    }
    public Boolean getCheckRecordList(List<AnnualDonationRecord> list,AnnualDonationRecord annualDonationRecord){
        Boolean bo=false;
        if(list!=null&&list.size()>0){
            for (AnnualDonationRecord annualDonationRecord1: list) {
                if(annualDonationRecord1!=null&&annualDonationRecord1.getDonationObject()!=null){
                    if(annualDonationRecord.getDonationObject().equals(annualDonationRecord1.getDonationObject())){
                        bo=true;
                        break;
                    }
                }
            }
        }
        return bo;
    }
}
